package com.yanghs.shiro.listener;

import com.yanghs.common.util.ConvertUtil;
import com.yanghs.shiro.session.IRedisRepository;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Date;
import java.util.Deque;

/**
 * @author yanghs
 * @Description:
 * @date 2018/3/13 21:10
 */
public class MySessionListener implements SessionListener {
    private static final Logger LOG = LoggerFactory.getLogger(MySessionListener.class);

    private IRedisRepository redisRepository;
    @Override
    public void onStart(Session session) {
        LOG.debug("创建会话："+session.getId()+"   时间："+ ConvertUtil.timeFormat(new Date()));
    }

    /*执行loginout*/
    @Override
    public void onStop(Session session) {
        String account = (String) session.getAttribute("account");
        Deque<Serializable> deque = redisRepository.getAccountSessions(account);
        if( deque!=null && deque.contains(session.getId())){
            deque.remove(session.getId());
            if(deque.size() > 0){
                redisRepository.saveAccountSessions(account,deque);
            }else{
                redisRepository.deleteAccountSessions(account);
            }
        }
        LOG.debug("结束会话："+session.getId()+"   时间："+ ConvertUtil.timeFormat(new Date()));
    }
    /*会话超时*/
    @Override
    public void onExpiration(Session session) {
        onStop(session);

        LOG.debug("会话过期："+session.getId()+"  时间："+ ConvertUtil.timeFormat(new Date()));
    }
    public IRedisRepository getRedisRepository() {
        return redisRepository;
    }

    public void setRedisRepository(IRedisRepository redisRepository) {
        this.redisRepository = redisRepository;
    }
}
